package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.eKnowAi.EKnowChatLog;
import com.ys.entity.eKnowAi.EKnowChatLogManage;
import com.ys.entity.sys.YsCol;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowChatLogManageService;
import com.ys.service.eKnowAi.EKnowChatLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/eKnowChatLog")
public class ApiInterEKnowChatLogController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterEKnowChatLogController.class);
    private static Long MENU_ID = 10142L;

    @Autowired
    private CommonApiService<EKnowChatLog> commonApiService;

    @Autowired
    private EKnowChatLogService eKnowChatLogService;

    @Autowired
    private EKnowChatLogManageService eKnowChatLogManageService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public EKnowChatLog setSeachSql(EKnowChatLog cond){
        cond.addField("A.UserId + '/' + U.UserName AS userName");//提问人
        cond.addField("M.ModelOwnName AS aiModelName");//模型名称
        cond.addField("S.SceneName AS sceneName");//场景名称
        //cond.addField("B.KnowledgeBaseName AS knowledgeBaseName");//知识库名称
        cond.addField("P.PromptName AS promptName");//提示词名称
        cond.addField("CASE WHEN A.Evaluate = '0' THEN '踩' WHEN A.Evaluate = '1' THEN '赞' ELSE '未评价' END evaluateTxt ");//评价
        cond.addField("CASE WHEN A.IsKnowledge = '0' THEN '否' WHEN A.IsKnowledge = '1' THEN '是' ELSE '未记录' END isKnowledgeTxt ");//是否用知识库问答（0否，1是，null未记录）

        cond.addLeftJoin("kjecp.dbo.TS_UserInfo U ON U.UserId = A.UserId AND U.UserId IS NOT NULL");
        cond.addLeftJoin("kjecp_eknow.dbo.EKnow_Scene S ON S.Id = A.SceneId AND S.Id IS NOT NULL");
        cond.addLeftJoin("kjecp_eknow.dbo.EKnow_Model M ON M.Id = A.AiModelId AND M.Id IS NOT NULL");
        cond.addLeftJoin("kjecp_eknow.dbo.EKnow_Prompt P ON P.Id = A.PromptId AND P.Id IS NOT NULL");
        //cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON B.Id = A.KnowledgeBaseId AND B.Id IS NOT NULL");
        //排序
        cond.setOrderby("A.CreateTime DESC");
        return  cond;
    }





    /**
     * 查询
     */
    @RequiresPermissions("eKnowChatLog:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute EKnowChatLog cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询日志出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute EKnowChatLog cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<EKnowChatLog> util = new ExportExcelUtils<>(new EKnowChatLog());
            String toFilePath = util.exportExcel(listData, listField, "逸知道Ai日志");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 聊天日志添加至管理页面
     */
    @PostMapping("/chatLogAddManage")
    @ResponseBody
    public JSONObject chatLogAddManage(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            int isSave = 0;
            for(String item:idArr){
                long id = Long.parseLong(item);//Id
                EKnowChatLog eKnowChatLogInfo  = new EKnowChatLog().setId(id).queryFirst();
                if(eKnowChatLogInfo!=null){
                    EKnowChatLogManage eKnowChatLogManage = new  EKnowChatLogManage();
                    eKnowChatLogManage.setOldLogId(id);
                    //内容=日志的问题+回答
                    eKnowChatLogManage.setContent(eKnowChatLogInfo.getQuestion()+"\n"+eKnowChatLogInfo.getAnswer());
                    eKnowChatLogManage.setUserId(ShiroUtils.getUserId());
                    eKnowChatLogManage.setIsSaveKnowledge(0);
                    int isAdd = eKnowChatLogManageService.add(eKnowChatLogManage);
                    if(isAdd>0){
                        EKnowChatLog eKnowChatLog = new EKnowChatLog();
                        eKnowChatLog.setId(id);
                        eKnowChatLog.setIsReSet(1);
                        eKnowChatLogService.update(eKnowChatLog);
                        isSave ++ ;
                    }
                }
            }
            if(isSave>0){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("聊天日志添加至管理页面出错：",e.getMessage(),e);
        }
        return result;


    }

    /**
     * 查看日志详情
     */
    @PostMapping("/eKnowChatLogDetailById")
    @ResponseBody
    public JSONObject eKnowChatLogDetailById(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            long id = Long.parseLong(params.get("id").toString());//id

            Map<String,Object> eKnowChatLog = new EKnowChatLog()
                    .setId(id)
                    .addField("A.UserId + '/' + U.UserName AS userName")//提问人
                    .addField("M.ModelOwnName AS aiModelName")//模型名称
                    .addField("S.SceneName AS sceneName")//场景名称
                    .addField("B.KnowledgeBaseName AS knowledgeBaseName")//知识库名称
                    .addField("P.PromptName AS promptName")//提示词名称
                    .addField("CASE WHEN A.Evaluate = '0' THEN '踩' WHEN A.Evaluate = '1' THEN '赞' ELSE '未评价' END evaluateTxt ")//评价
                    .addField("CASE WHEN A.IsKnowledge = '0' THEN '否' WHEN A.IsKnowledge = '1' THEN '是' ELSE '未记录' END isKnowledgeTxt ")//是否用知识库问答（0否，1是，null未记录）

                    .addLeftJoin("kjecp.dbo.TS_UserInfo U ON U.UserId = A.UserId")
                    .addLeftJoin("kjecp_eknow.dbo.EKnow_Scene S ON S.Id = A.SceneId")
                    .addLeftJoin("kjecp_eknow.dbo.EKnow_Model M ON M.Id = A.AiModelId")
                    .addLeftJoin("kjecp_eknow.dbo.EKnow_Prompt P ON P.Id = A.PromptId")
                    .addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON B.Id = A.KnowledgeBaseId")
                    .queryFirstMap();

            if(eKnowChatLog!=null){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                result.put("eKnowChatLog", eKnowChatLog);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("逸知道查看日志详情出错：",e.getMessage(),e);
        }
        return result;
    }

}